package cn.iocoder.yudao.module.erp.controller.admin.deppurchase;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.bpm.service.task.BpmTasktooServiceImpl;
import cn.iocoder.yudao.module.erp.controller.admin.deppurchase.vo.DepPurchasePageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.deppurchase.vo.DepPurchaseRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.deppurchase.vo.DepPurchaseSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.deppurchaseitem.vo.DepPurchaseItemPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.deppurchaseitem.vo.DepPurchaseItemRespVO;
import cn.iocoder.yudao.module.erp.convert.deppurchase.DeptPurchaseConvert;
import cn.iocoder.yudao.module.erp.convert.deppurchaseitem.DepPurchaseItemConvert;
import cn.iocoder.yudao.module.erp.dal.dataobject.deppurchase.DepPurchaseDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.deppurchaseitem.DepPurchaseItemDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.relationship.RelationshipDO;
import cn.iocoder.yudao.module.erp.service.deppurchase.DepPurchaseService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductUnitService;
import cn.iocoder.yudao.module.erp.service.purchase.ErpSupplierService;
import cn.iocoder.yudao.module.erp.service.relationship.RelationshipService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - ERP 科室采购申请单")
@RestController
@RequestMapping("/erp/dep-purchase")
@Validated
public class DepPurchaseController {

    @Resource
    private DepPurchaseService depPurchaseService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private ErpProductUnitService erpProductUnitService;
    @Resource
    private ErpSupplierService erpSupplierService;

    @Resource
    private RelationshipService relationshipService;

    @Autowired
    private BpmTasktooServiceImpl bpmTasktooService;

    //    获取配置文件中的路由名  总务物资
    @Value("${erp.department.taskname}")
    private String DEPARTMENT_KEY1;

    @PostMapping("/create")
    @Operation(summary = "创建ERP 科室采购申请单")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:create')")
    public CommonResult<Long> createDepPurchase(@Valid @RequestBody DepPurchaseSaveReqVO createReqVO) {
        if (createReqVO != null) {
            //根据保存单数据获取项产品ids
            List<DepPurchaseItemDO> depPurchaseItems = createReqVO.getDepPurchaseItems();
            List<Long> productIds = new ArrayList<>();
            //List<Long> productIds = convertList(depPurchaseItems, DepPurchaseItemDO::getProductId);
            for (DepPurchaseItemDO depPurchaseItemDO : depPurchaseItems) {
                productIds.add(depPurchaseItemDO.getProductId());
            }
            //根据产品ids获取供应商ids
            List<RelationshipDO> relationships = relationshipService.getRelationshipsByProductIds(productIds);
            List<Long> supplierIds = new ArrayList<>();
            for (RelationshipDO relationshipDO : relationships) {
                if (relationshipDO.getSort() == 1) {
                    supplierIds.add(relationshipDO.getSupplierId());
                    //获取的供应商id赋进保存单数据
                    for (DepPurchaseItemDO depPurchaseItemDO : depPurchaseItems) {
                        if (depPurchaseItemDO.getProductId().equals(relationshipDO.getProductId())) {
                            depPurchaseItemDO.setSupplierId(relationshipDO.getSupplierId());
                        }
                    }
                }
            }
            //根据供应商ids获取deptid
            List<ErpSupplierDO> suppliers = erpSupplierService.getSupplierList(supplierIds);
            //List<Long> deptIds = new ArrayList<>();
            for (ErpSupplierDO supplierDO : suppliers) {
                //deptIds.add(supplierDO.getDeptId());
                ////获取的供应商deptid赋进保存单数据
                for (DepPurchaseItemDO depPurchaseItemDO : depPurchaseItems) {
                    if (depPurchaseItemDO.getSupplierId().equals(supplierDO.getId())) {
                        depPurchaseItemDO.setSupplierDeptId(supplierDO.getDeptId());
                    }
                }
            }
            createReqVO.setDepPurchaseItems(depPurchaseItems);
        }
        return success(depPurchaseService.createDepPurchase(getLoginUserId(), createReqVO));
    }

    @PostMapping("/fenfacreate")
    @Operation(summary = "采购分发,以及调拨")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:update')")
    public CommonResult<Boolean> fenfacreateDepPurchase(@Valid @RequestBody DepPurchaseSaveReqVO updateReqVO) {
        depPurchaseService.fenfacreateDepPurchase(getLoginUserId(), updateReqVO);
        return success(true);
    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP 科室采购申请单")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:update')")
    public CommonResult<Boolean> updateDepPurchase(@Valid @RequestBody DepPurchaseSaveReqVO updateReqVO) {
        depPurchaseService.updateDepPurchase(updateReqVO);
        return success(true);
    }

    @PutMapping("/updatestatus")
    @Operation(summary = "更新ERP 科室采购申请单")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:update')")
    public CommonResult<Boolean> updatestatus(@Valid String integraId) {
        depPurchaseService.updateStatus(integraId);
        return success(true);
    }

    @PutMapping("/updateDepPurchaseStatusByIntegraId")
    @Operation(summary = "更新ERP 科室采购申请单")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:update')")
    public CommonResult<Boolean> updateStatusByIntegraId(@RequestParam("integraId") String integraId, @RequestParam("status") Integer status) {
        depPurchaseService.updateStatusByIntegraId(integraId,status);
        return success(true);
    }


    @DeleteMapping("/delete")
    @Operation(summary = "删除ERP 科室采购申请单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:delete')")
    public CommonResult<Boolean> deleteDepPurchase(@RequestParam("id") Long id) {
        depPurchaseService.deleteDepPurchase(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP 科室采购申请单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:query')")
    public CommonResult<DepPurchaseRespVO> getDepPurchase(@RequestParam("id") Long id) {
        DepPurchaseRespVO depPurchase = depPurchaseService.getDepPurchase(id);
        return success(depPurchase);
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP 科室采购申请单分页")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:query')")
    public CommonResult<PageResult<DepPurchaseRespVO>> getDepPurchasePage(@Valid DepPurchasePageReqVO pageReqVO) {
        PageResult<DepPurchaseDO> pageResult = depPurchaseService.getDepPurchasePage(pageReqVO);
        List<Long> userIds = convertList(pageResult.getList(), DepPurchaseDO::getNewId);
        // 用ids查询用户Map
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);

        List<Long> deptIds = convertList(pageResult.getList(), DepPurchaseDO::getNewDeptId);

        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(deptIds);

        return success(new PageResult<>(DeptPurchaseConvert.INSTANCE.convertList(pageResult.getList(), userMap, deptMap),
                pageResult.getTotal()));
    }

    @GetMapping("/workflowPage")
    @Operation(summary = "获取工作流采购申请单待办数据")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:query')")
    public CommonResult<PageResult<DepPurchaseRespVO>> getWorkflowPage(@Valid DepPurchasePageReqVO pageReqVO) {

//        查询待办数据
        List<Task> taskTodoToo = bpmTasktooService.getTaskTodoToo(getLoginUserId(), DEPARTMENT_KEY1);
        //        把taskTodoToo集合中所有数据的process_instance_id提取出来成一个集合
        // 检查 taskTodoPage 是否为空
        if (taskTodoToo == null || taskTodoToo.isEmpty()) {
            return success(new PageResult<>());
        }
        List<String> processInstanceIds = taskTodoToo.stream().map(Task::getProcessInstanceId).collect(Collectors.toList());
        pageReqVO.setProcessInstanceIds(processInstanceIds);
//        根据流程实例过滤的数据
        PageResult<DepPurchaseDO> pageResult = depPurchaseService.getDepPurchasePage(pageReqVO);

        List<Long> userIds = convertList(pageResult.getList(), DepPurchaseDO::getNewId);
        // 用ids查询用户Map
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);

        List<Long> deptIds = convertList(pageResult.getList(), DepPurchaseDO::getNewDeptId);

        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(deptIds);

        return success(new PageResult<>(DeptPurchaseConvert.INSTANCE.convertList(pageResult.getList(), userMap, deptMap),
                pageResult.getTotal()));
    }



    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP 科室采购申请单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDepPurchaseExcel(@Valid DepPurchasePageReqVO pageReqVO,
                                       HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DepPurchaseDO> list = depPurchaseService.getDepPurchasePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "ERP 科室采购申请单.xls", "数据", DepPurchaseRespVO.class,
                BeanUtils.toBean(list, DepPurchaseRespVO.class));
    }

    // ==================== 子表（ERP 科室采购申请项） ====================

    @GetMapping("/dep-purchase-item/newlist-by-order-id")
    @Operation(summary = "获得ERP 科室采购申请项列表")
    @Parameter(name = "orderId", description = "科室采购订单编号")
    public CommonResult<List<DepPurchaseItemDO>> getnewDepPurchaseItemListByOrderId(@RequestParam("orderId") Long orderId) {
        return success(depPurchaseService.getnewDepPurchaseItemListByOrderId(orderId));
    }


    @GetMapping("/dep-purchase-item/list-by-order-id")
    @Operation(summary = "获得ERP 科室采购申请项列表")
    @Parameter(name = "orderId", description = "科室采购订单编号")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:query')")
    public CommonResult<List<DepPurchaseItemRespVO>> getDepPurchaseItemListByOrderId(@RequestParam("orderId") Long orderId) {
        List<DepPurchaseItemDO> depPurchaseItemListByOrderId = depPurchaseService.getDepPurchaseItemListByOrderId(orderId);

        // 提取供应商ids
        List<Long> supplierIds = convertList(depPurchaseItemListByOrderId, DepPurchaseItemDO::getSupplierId);
        Map<Long, ErpSupplierDO> supplierMap = null;
        if (supplierIds != null && supplierIds.size() != 0) {
            supplierMap = erpSupplierService.getSupplierMap(supplierIds);
        }

        return success(DepPurchaseItemConvert.INSTANCE.convertList(depPurchaseItemListByOrderId, supplierMap));
    }

    @GetMapping("/getDepPurchaseItemList")
    @Operation(summary = "获得ERP 科室采购申请项列表")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:query')")
    public CommonResult<List<DepPurchaseItemRespVO>> getDepPurchaseItemList(@Valid DepPurchaseItemPageReqVO pageReqVO) {
        List<DepPurchaseItemDO> depPurchaseItemList = depPurchaseService.getDepPurchaseItemList(pageReqVO);
        // 提取供应商ids
        List<Long> supplierIds = convertList(depPurchaseItemList, DepPurchaseItemDO::getSupplierId);
        Map<Long, ErpSupplierDO> supplierMap = null;
        if (supplierIds != null && supplierIds.size() != 0) {
            supplierMap = erpSupplierService.getSupplierMap(supplierIds);
        }
        List<Long> deptIds = convertList(depPurchaseItemList, DepPurchaseItemDO::getDeptId);

        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(deptIds);

        return success(DepPurchaseItemConvert.INSTANCE.convertList1(depPurchaseItemList, deptMap, supplierMap));
    }

    @PutMapping("/submit")
    @Operation(summary = "报送给科室采购申请单")
    @PreAuthorize("@ss.hasPermission('erp:dep-purchase:submit')")
    public CommonResult<Boolean> submit(@Valid @RequestBody DepPurchaseSaveReqVO createReqVO) {
        depPurchaseService.submit(getLoginUserId(), createReqVO);
        return success(true);
    }
}